# -*- coding: utf-8 -*-

"""
启动入口
"""

# import sys
# from sanic import exceptions
from sanic import Sanic
# from sanic import Blueprint
from sanic_ext import Extend

from api import bp_api_v1
from api.index import IndexView
# from config import CustomConfig
from server.listener import (
    before_app_start,
    before_app_stop,
    after_app_start,
    after_app_stop,
)
from server.middleware import (
    inject_session,
    close_session,
)


# app = Sanic(__name__, config=CustomConfig)
app = Sanic("gbcms", env_prefix="GBCMS_")
Extend(app)

# 注册首页
app.add_route(IndexView.as_view(), "/")

# 注册API路由
app.blueprint(bp_api_v1)

# 静态文件，API接口的 logo，favicon.ico文件
app.static('/', './static', name='静态文件')

# WebUI
# app.static('/', './ui/index.html', name="WebUI首页")
app.static('/ui', './ui', name='WebUI')

# 系统启动前，触发事件
app.register_listener(before_app_start, "before_server_start")

# 系统启动后，触发事件
app.register_listener(after_app_start, "after_server_start")

# 系统关闭前，触发事件
app.register_listener(before_app_stop, "before_server_stop")

# 系统关闭后，触发事件
app.register_listener(after_app_stop, "after_server_stop")

# 注册请求中间件
app.register_middleware(inject_session, attach_to="request")

# 注册响应中间件
app.register_middleware(close_session, attach_to="response")

# # 获取所有路由名称
# get_route_list(app)

# 默认 127.0.0.1:8000
app.config.HOST = "0.0.0.0"
app.config.PORT = 8000
app.config.FALLBACK_ERROR_FORMAT = 'auto'  # 'json'
app.config.ACCESS_LOG = True
app.config.LOG_MAXBYTES = 5242880
app.config.LOG_BACKUPCOUNT = 10
app.config.LOG_FORMATTER = "%(asctime)s [%(process)d] [%(filename)s:%(lineno)d] [%(levelname)s] %(message)s"
app.config.LOG_FILE_PATH = "./log/"
app.config.LOG_FILE_NAME = "gbcms"

# db_settings = {
#     'KEY': 'VAL',
# }
# app.config.update(db_settings)


if __name__ == "__main__":
    # 开发环境使用，不要注释，命令行方式启动不受影响
    # app.run(host=app.config.HOST, port=app.config.PORT, debug=True)
    # app.run(host=app.config.HOST, port=app.config.PORT, debug=True, auto_reload=True, workers=multiprocessing.cpu_count() // 5)
    # app.run(host=app.config.HOST, port=app.config.PORT, debug=True, auto_reload=True, fast=True)
    app.run(
        host=app.config.get('HOST', '0.0.0.0'),
        port=app.config.get('PORT', 80),
        debug=app.config.get('DEBUG', False),
        # auto_reload=True,
        single_process=True,
    )
